package com.lechuang.cunpinke.manager;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 下载管理器，方便在web中下载文件
 * 作者：尹松涛
 * 邮箱：yinsongtaoshmily@outlook.com
 * 日期：2017/9/9
 * 时间：08:44
 */

public class MyDownLoadManager {
    public static volatile MyDownLoadManager instance;
    private DownloadManager manager;
    private Map<String, DownLoadDesc> downLoadMapping;

    private MyDownLoadManager(Context context) {
        manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        downLoadMapping = new HashMap<>();
    }

    public static MyDownLoadManager getInstance(Context context) {
        if (instance == null) {
            synchronized (MyDownLoadManager.class) {
                if (instance == null) {
                    instance = new MyDownLoadManager(context);
                }
            }
        }
        return instance;
    }

    /**
     * 发起让系统下载文件
     *
     * @param url      下载url
     * @param title    进度条的标题
     * @param desc     进度条的描述
     * @param fileName 保存的文件名
     */
    public synchronized void startDownLoad(String url, String title, String desc, String fileName) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(fileName)) return;
        if (downLoadMapping.containsKey(url)) {
            int status = queryDownLoadStatus(downLoadMapping.get(url).downLoadId);
            boolean isReDownLoad = false;
            switch (status) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    ToastManager.getInstance().showLongToast("文件已经下载成功");
                    downLoadMapping.remove(url);
                    break;
                case DownloadManager.STATUS_FAILED:
                    isReDownLoad = true;
                    break;
                case DownloadManager.STATUS_PAUSED:
                    ToastManager.getInstance().showLongToast("文件下载被暂停请开始下载");
                    break;
                case DownloadManager.STATUS_RUNNING:
                    ToastManager.getInstance().showLongToast("文件正在下载...");
                    break;
                case DownloadManager.STATUS_PENDING:
                    ToastManager.getInstance().showLongToast("等待下载...");
                    break;
            }
            if (!isReDownLoad) return;
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle(title == null ? "" : title);
        request.setDescription(desc == null ? "" : desc);
        File save = new File(FolderManager.getAppFolder(), fileName);
        request.setDestinationUri(Uri.fromFile(save));
        long downLoadId = manager.enqueue(request);
        DownLoadDesc downLoadDesc = new DownLoadDesc(save, downLoadId);
        downLoadMapping.put(url, downLoadDesc);
    }

    /**
     * 查询下载状态
     *
     * @param downLoadId
     * @return
     */
    public synchronized int queryDownLoadStatus(long downLoadId) {
        if (downLoadMapping.isEmpty()) return -1;
        boolean isMyFile = false;
        for (DownLoadDesc desc : downLoadMapping.values()) {
            if (desc.downLoadId == downLoadId) {
                isMyFile = true;
                break;
            }
        }
        if (!isMyFile) return -1;
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downLoadId);
        Cursor cursor = manager.query(query);
        if (cursor == null || !cursor.moveToFirst()) {
            cursor.close();
            return -1;
        }
        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        cursor.close();
        return status;
    }

    /**
     * 下载文件描述
     */
    class DownLoadDesc {
        public File filePath;
        public long downLoadId;

        public DownLoadDesc(File filePath, long downLoadId) {
            this.filePath = filePath;
            this.downLoadId = downLoadId;
        }
    }

}
